package org.codehaus.activemq.message;

import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import javax.jms.JMSException;
import javax.jms.MessageNotWriteableException;
import javax.jms.ObjectMessage;

public class ActiveMQObjectMessage extends ActiveMQMessage
  implements ObjectMessage
{
  private Serializable object;

  public int getPacketType()
  {
    return 8;
  }

  public ActiveMQMessage shallowCopy()
    throws JMSException
  {
    ActiveMQObjectMessage other = new ActiveMQObjectMessage();
    initializeOther(other);
    other.object = this.object;
    return other;
  }

  public ActiveMQMessage deepCopy()
    throws JMSException
  {
    return shallowCopy();
  }

  public void clearBody()
    throws JMSException
  {
    super.clearBody();
    this.object = null;
  }

  public void setObject(Serializable newObject)
    throws JMSException
  {
    if (this.readOnlyMessage) {
      throw new MessageNotWriteableException("The message is read-only");
    }
    this.object = newObject;
  }

  void setObjectPayload(Object newObject) {
    this.object = ((Serializable)newObject);
  }

  public Serializable getObject()
    throws JMSException
  {
    if (this.object == null) {
      try {
        super.buildBodyFromBytes();
      }
      catch (IOException ioe) {
        JMSException jmsEx = new JMSException("failed to build body from bytes");
        jmsEx.setLinkedException(ioe);
        throw jmsEx;
      }
    }
    return this.object;
  }

  protected void writeBody(DataOutput dataOut)
    throws IOException
  {
    ObjectOutputStream objOut = new ObjectOutputStream((OutputStream)dataOut);
    objOut.writeObject(this.object);
    objOut.flush();
  }

  protected void readBody(DataInput dataIn)
    throws IOException
  {
    ObjectInputStream objIn = new ObjectInputStream((InputStream)dataIn);
    try {
      this.object = ((Serializable)objIn.readObject());
      objIn.close();
    }
    catch (ClassNotFoundException ex) {
      throw new IOException(ex.getMessage());
    }
  }
}